﻿Imports System
Imports System.Data.Common
Imports System.Threading
Imports System.Transactions

Namespace System.Workflow.Runtime.Hosting
    Friend NotInheritable Class SharedConnectionInfo
        Implements IDisposable
        ' Methods
        Friend Sub New(ByVal dbResourceAllocator As DbResourceAllocator, ByVal transaction As Transaction, ByVal wantPromotable As Boolean, ByVal handle As ManualResetEvent)
            If (handle Is Nothing) Then
                Throw New ArgumentNullException("handle")
            End If
            Me.handle = handle
            If wantPromotable Then
                Me.connection = dbResourceAllocator.OpenNewConnection
                Me.connection.EnlistTransaction(transaction)
            Else
                Dim promotableSinglePhaseNotification As New LocalTransaction(dbResourceAllocator, handle)
                transaction.EnlistPromotableSinglePhase(promotableSinglePhaseNotification)
                Me.connection = promotableSinglePhaseNotification.Connection
                Me.localTransaction = promotableSinglePhaseNotification.Transaction
            End If
        End Sub

        Public Sub Dispose()
            Me.Dispose(True)
            GC.SuppressFinalize(Me)
        End Sub

        Private Sub Dispose(ByVal disposing As Boolean)
            If ((Not Me.disposed AndAlso (Me.localTransaction Is Nothing)) AndAlso (Not Me.connection Is Nothing)) Then
                Me.connection.Dispose
            End If
            Me.disposed = True
        End Sub


        ' Properties
        Friend ReadOnly Property DBConnection As DbConnection
            Get
                Return Me.connection
            End Get
        End Property

        Friend ReadOnly Property DBTransaction As DbTransaction
            Get
                Return Me.localTransaction
            End Get
        End Property


        ' Fields
        Private ReadOnly connection As DbConnection
        Private disposed As Boolean
        Private handle As ManualResetEvent
        Private ReadOnly localTransaction As DbTransaction
    End Class
End Namespace

